package com.bytesizedhosting.api.android.darthcrap.screens;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bytesizedhosting.api.android.darthcrap.ExtendedActivity;
import com.bytesizedhosting.api.android.darthcrap.R;
import com.bytesizedhosting.api.android.darthcrap.api.APIController;
import com.bytesizedhosting.api.android.darthcrap.api.APIRetriever;
import com.bytesizedhosting.api.android.darthcrap.api.APIController.RetrievalState;

public class LoadingScreen extends ExtendedActivity implements APIRetriever {
	private static final int MESSAGE_CHANGE_STATE = 0;
	private static final int MESSAGE_RESET_GUI = 1;
	private static final int MESSAGE_CHANGE_MESSAGE = 2;
	private static final int MESSAGE_SHOW_ERROR = 3;

	Handler objHandler = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loadingscreen);
        final Activity objActivity = this;
        
        findViewById(R.id.btnAssociate).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View objView) {
				switchTo(KeySetScreen.class,false,true);
			}
		});
        findViewById(R.id.btnRetry).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View objView) {
				restartLoad();
			}
		});
        findViewById(R.id.btnUseCache).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View objView) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						objHandler.sendMessage(objHandler.obtainMessage(0,MESSAGE_RESET_GUI,0,null));
						try {
							Thread.sleep(500);
						}
						catch (InterruptedException objException) {}
						if (APIController.loadFile(objActivity)) {
							retrieveStateChanged(APIController.RetrievalState.FINISHING,false);
							try {
								Thread.sleep(500);
							}
							catch (InterruptedException objException) {}
							retrieveStateChanged(APIController.RetrievalState.READY,false);
						}
						else {
							objHandler.sendMessage(objHandler.obtainMessage(0,MESSAGE_SHOW_ERROR,R.string.loading_state_load_failure,null));
						}
					}
				}).start();
			}
		});
        this.objHandler = new Handler() {
        	public void handleMessage(Message objMessage) {
        		if (objMessage.arg1 == MESSAGE_CHANGE_STATE) {
	        		boolean boolHadError = (objMessage.arg2==1?true:false);
	        		RetrievalState objState = (RetrievalState)objMessage.obj;
	        		
	        		if (boolHadError) {
	        			switch (objState) {
	        			case LOADING:
	        			case CONNECTING:
	        			case RETRIEVING:
	        			case PARSING:
	        			case KEYCHECK:
	        			case SAVING:
	        				showError(objState.getErrorMessageID());
	        				break;
	        			}
	        		}
	        		else {
	        			switch (objState) {
	        			case LOADING:
	        			case CONNECTING:
	        			case RETRIEVING:
	        			case PARSING:
	        			case SAVING:
	        			case FINISHING:
	        				changeMessage(objState.getNormalMessageID());
	        				break;
	        			case READY:
	        				switchTo(MainScreen.class,true,false,new IntentConfigurator() {
	        					@Override
	        					public void configure(Intent objIntent) {
        							if (objActivity.getIntent().hasExtra("code")) {
	        								objIntent.putExtra("code", objActivity.getIntent().getExtras().getInt("code"));
	        						}
	        					}
	        				});
	        				break;
	        			}
	        		}
        		}
        		else if (objMessage.arg1 == MESSAGE_RESET_GUI) {
        			resetGUI();
        		}
        		else if (objMessage.arg1 == MESSAGE_CHANGE_MESSAGE) {
        			changeMessage(objMessage.arg2);
        		}
        		else if (objMessage.arg1 == MESSAGE_SHOW_ERROR) {
        			showError(objMessage.arg2);
        		}
        	}
        };
        this.restartLoad();
    }

	public void retrieveStateChanged(RetrievalState objState, boolean boolHadError) {
		objHandler.sendMessage(objHandler.obtainMessage(0,MESSAGE_CHANGE_STATE,(boolHadError?1:0),objState));
	}
	
	private void changeMessage(int intMessageID) {
		((TextView)findViewById(R.id.lblMessage)).setText(intMessageID);
	}
	
	private void showError(int intMessageID) {
		changeMessage(intMessageID);
		findViewById(R.id.pbLoading).setVisibility(View.GONE);
		findViewById(R.id.imgError).setVisibility(View.VISIBLE);
		if (intMessageID == R.string.loading_state_noapikey_error || intMessageID == R.string.loading_state_nosuchkey_error) {
			findViewById(R.id.btnAssociate).setVisibility(View.VISIBLE);
		}
		else {
			Button btnUseCache = (Button)findViewById(R.id.btnUseCache);
			findViewById(R.id.btnRetry).setVisibility(View.VISIBLE);
			btnUseCache.setVisibility(View.VISIBLE);
			btnUseCache.setEnabled(APIController.canLoadFile(this));
		}
	}
	
	public void resetGUI() {
		findViewById(R.id.pbLoading).setVisibility(View.VISIBLE);
		findViewById(R.id.imgError).setVisibility(View.GONE);
		findViewById(R.id.btnAssociate).setVisibility(View.GONE);
		findViewById(R.id.btnRetry).setVisibility(View.GONE);
		findViewById(R.id.btnUseCache).setVisibility(View.GONE);
		retrieveStateChanged(APIController.RetrievalState.LOADING,false);
	}
	
	public void restartLoad() {
		resetGUI();
        APIController.retrieve(this,this,true,true);
	}
	
    public void onActivityResult(int intRequestCode, int intResultCode, Intent objIntent) { 
    	if (intRequestCode == 0 && intResultCode != RESULT_CANCELED) {
    		this.restartLoad();
    	}
   	} 
}